import Ext, { isFirefox } from "@/common/web_extension"
import { delay, } from '@/common/ts_utils';

export const panelUrl = Ext.runtime.getURL('popup_panel.html')

export const getPlayTab = async (tabId?: number) => {
    return await new Promise((resolve) => {
        Ext.tabs.query({ active: true }, (tabs: any[]) => {
            resolve(tabs.filter((tab) => tab.url !== panelUrl)[0]);
        })
    })
}

export const getTab = async (id: number) => {
    return await new Promise((resolve) => {
        Ext.tabs.query({}, (tabs: any[]) => {
            resolve(tabs.filter((tab) => tab.id === id)[0]);
        })
    })
}

export const getPanelTab = async () => {
    return await new Promise((resolve) => {
        Ext.tabs.query({ url: panelUrl }, (tabs: any[]) => {
            resolve(tabs[0]);
        })
    })
}
// 显示控制面板
export const showPanelWindow = async ({ params, minimized }: { params?: any, minimized?: boolean } = {}) => {
    const size = {
        width: 850,
        height: 775,
    };

    const urlQuery = Object.keys(params || {})
        .map((key) => {
            return `${key}=${params[key]}`;
        })
        .join('&');
    const base = panelUrl;
    const url = urlQuery.length > 0 ? `${base}?${urlQuery}` : base;

    return Ext.windows
        .create({
            url,
            type: 'popup',
            state: minimized ? 'minimized' : 'normal',
            ...(!minimized ? size : {}),
        })
        .then((win: any) => {
            // because closing of side_panel sends the IDE to background
            const isEdge = navigator.userAgent.includes('Edg');
            if (isEdge) {
                Ext.runtime.sendMessage({
                    type: 'BringIDEToFront',
                    windowId: win.id,
                    delay: 2500, // 500ms + the delay in the next line
                });
            }

            if (!isFirefox()) return;

            // Refer to https://bugzilla.mozilla.org/show_bug.cgi?id=1425829
            // Firefox New popup window appears blank until right-click
            return delay(() => {
                return Ext.windows.update(win.id, {
                    width: size.width + 1,
                    height: size.height + 1,
                    state: 'normal',
                });
            }, 1000);
        })
        .then(() => delay(() => true, 2000));
}
